//
//  DetailViewController.m
//  rss_reader
//
//  Created by Oleg Soldatoff on 4/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DetailViewController.h"

@implementation DetailViewController
@synthesize link    = _link;
@synthesize webView = _webView;
@synthesize loaded  = _loaded;
@synthesize fullPageScrollHeight = _fullPageScrollHeight;
@synthesize userPageScrollHeight = _userPageScrollHeight;

@synthesize backButton = _backButton;
@synthesize forwardButton = _forwardButton;
@synthesize refreshButton = _refreshButton;
@synthesize stopButton = _stopButton;
@synthesize launchButton = _launchButton;

@synthesize willReadState = willReadState;
@synthesize base = _base;

- (void) releaseProps {
  
  self.link = nil;
  self.webView = nil;
  self.backButton = nil;
  self.forwardButton = nil;
  self.refreshButton = nil;
  self.stopButton = nil;
  self.launchButton = nil;

}

- (void)dealloc {
 
  [_base release];
  _base = nil;
  [self releaseProps];
  [super dealloc];
  
}

#pragma mark - Managing the detail item


- (void)viewDidLoad {
  
  [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
  
  self.webView = [[[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 372.0)]autorelease];
  [self.webView setDelegate: self];

  [self.view addSubview:self.webView];
  [self  addScrollViewListener];
  
  
  
    
  
  UIBarButtonItem *willReadButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(articleReadStatus:)] autorelease];
   
  if (self.willReadState == YES) willReadButton.tintColor = [UIColor blueColor];
  self.navigationItem.rightBarButtonItem = willReadButton;
   
  
  
  UIToolbar *browserToolBar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 372, 320, 44)]autorelease];
      browserToolBar.barStyle = UIBarStyleDefault;
  
    self.backButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_arrow_left.png"] landscapeImagePhone:[UIImage imageNamed:@"icon_arrow_left.png"] style: UIBarButtonItemStylePlain target: self action: @selector(goBack)] autorelease];
    self.backButton.width = 51;
    self.backButton.enabled = NO;
  
    self.forwardButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_arrow_right.png"] landscapeImagePhone:[UIImage imageNamed:@"icon_arrow_right.png"] style: UIBarButtonItemStylePlain target: self action: @selector(goForward)] autorelease];
    self.forwardButton.width = 51;
    self.forwardButton.enabled = NO;
 
  UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_refresh.png"] landscapeImagePhone:[UIImage imageNamed:@"icon_refresh.png"] style: UIBarButtonItemStylePlain target: self action: @selector(refresh:)] autorelease];
      refreshButton.width = 51;
  
  self.stopButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_delete.png"] landscapeImagePhone:[UIImage imageNamed:@"icon_delete.png"] style: UIBarButtonItemStylePlain target: self action: @selector(stopLoading)] autorelease];
  self.stopButton.width = 51;
      self.stopButton.enabled = NO;
  
  UIBarButtonItem *launchButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_upload.png"] landscapeImagePhone:[UIImage imageNamed:@"icon_upload.png"] style: UIBarButtonItemStylePlain target: self action: @selector(launchWithSafari:)] autorelease];
  launchButton.width = 51;
  
    browserToolBar.items = [NSArray arrayWithObjects:self.backButton, self.forwardButton, refreshButton, self.stopButton, launchButton, nil];
  
    [self.view addSubview:browserToolBar];
  
}

- (void) articleReadStatus:(id) sender {
  
  if (self.willReadState == YES) {
    [self.base articleDidReadWihStatus:self.link];
  }
  else {
    [self.base articleWillRead:self.link];
  }
  
  self.willReadState = !self.willReadState;
  [self.navigationController popViewControllerAnimated:YES];
}


- (void) refresh:(id)sender {
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.link]]];
}

- (void)launchWithSafari:(id)sender {
  [[UIApplication sharedApplication] openURL: self.webView.request.URL];
}

- (void) goBack {  
    [self.webView goBack];
}

- (void) goForward {
  [self.webView goForward];
}

- (void) stopLoading {
  [self.webView stopLoading];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    if (webView.canGoBack) {
          self.backButton.enabled = YES;
     } else {
          self.backButton.enabled = NO;
    }
  
  if (webView.canGoForward) {
        self.forwardButton.enabled = YES;
      } else {
        self.forwardButton.enabled = NO;
      }
    
  self.stopButton.enabled = YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
  
  self.stopButton.enabled = NO;
  
  //NSLog(@"To set up to scroll");
  if ( self.loaded == NO ) {
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.body.scrollTop = %d",self.userPageScrollHeight]];
    self.loaded = YES;
  }
  
  self.fullPageScrollHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] intValue];
  
  
}


- (void) addScrollViewListener
{
  UIScrollView* currentScrollView;
  for (UIView* subView in self.webView.subviews) {
    if ([subView isKindOfClass:[UIScrollView class]]) {
      currentScrollView = (UIScrollView*)subView;
      currentScrollView.delegate = self;
      currentScrollView.scrollsToTop = YES;
    }
  }
}



- (void)viewDidUnload
{
    [self releaseProps];
  self.base = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (void)viewWillAppear:(BOOL)animated {

  

  NSURL *url = [NSURL URLWithString:self.link];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  
  //Load the request in the UIWebView.
  [self.webView loadRequest:request];
  self.webView.scalesPageToFit = YES;
  self.loaded = NO;
 
  [super viewWillAppear:animated];

}



- (void)viewWillDisappear:(BOOL)animated { 
 
   self.loaded = NO;
  [super viewWillDisappear:animated];

}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //self.title = NSLocalizedString(@"Detail", @"Detail");
        self.base = [[[DataBase alloc]init]autorelease];
    }
    return self;
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
  
  self.fullPageScrollHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] intValue];
   self.userPageScrollHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue];
   int pageScrollHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"screen.height"] intValue];

   if (self.userPageScrollHeight + pageScrollHeight *2 +100 > self.fullPageScrollHeight) {
//     [self.navigationController setNavigationBarHidden:YES animated:YES];
   }
  
  // NSLog(@"Here to calc user scroll - %d", self.userPageScrollHeight);
  //NSLog(@"%d +++ %d ++++ %d ", self.userPageScrollHeight, self.fullPageScrollHeight, pageScrollHeight);

}

@end
